<template>
	<view class="team-page">
		<!-- 顶部选项卡 -->
		<view class="tabs-container">
			<uni-segmented-control :current="currentTab" :values="tabs" @clickItem="onTabClick" styleType="button"
				activeColor="#ff6b35"></uni-segmented-control>
		</view>

		<!-- 内容区域 -->
		<view class="content">
			<!-- 搜索和添加按钮 -->
			<view class="action-bar">
				<uni-search-bar @confirm="search" @input="onSearchInput" placeholder="搜索团队成员" radius="20"
					clearButton="auto" cancelButton="none" style="flex:1;"></uni-search-bar>
				<button class="add-btn" @click="addMember">
					<uni-icons type="plus" size="20" color="#fff"></uni-icons>
					添加
				</button>
			</view>

			<!-- 成员列表 -->
			<scroll-view class="member-list" id="member" scroll-y :style="{height:height}">
				<view class="member-item" v-for="member in filteredMembers" :key="member._id">
					<view class="member-info">
						<view class="avatar">
							<text class="avatar-text">{{ getAvatarText(member.nickName) }}</text>
						</view>
						<view class="info-content">
							<view class="name-row">
								<text class="name">{{ member.nickName}}【{{member.name}}】</text>
								<text class="role-tag" :style="{backgroundColor: getRoleColor(member.role)}">
									{{ getRoleText(member.role) }}
								</text>
							</view>
							<text class="phone">{{ member.phone }}</text>
							<text class="agency" v-if="member.agency">{{ member.agency }}</text>
						</view>
					</view>
					<view class="member-status">
						<text class="status" :class="{online: member.isOnline}">
							{{ member.isOnline ? '在岗' : '离岗' }}
						</text>
						<view class="actions">
							<uni-icons type="locked" size="20" color="#666"
								@click="showChangePassword(member)"></uni-icons>
							<uni-icons :type="member.status === 1 ? 'minus' : 'plus'" size="20"
								:color="member.status === 1 ? '#ff4757' : '#2ecc71'"
								@click="toggleMemberStatus(member)">
							</uni-icons>
						</view>
					</view>
				</view>
				<view v-if="filteredMembers.length ==0">
					暂无请添加
				</view>
			</scroll-view>
		</view>
		<!-- 修改密码弹窗 -->
		<uni-popup ref="passwordPopup" type="dialog">
			<uni-popup-dialog mode="input" title="修改/复制-密码" cancelText="复制密码" :before-close="true" @close="copyPassword"
				placeholder=" 输入新密码" @confirm="confirmChangePassword">
			</uni-popup-dialog>
		</uni-popup>

		<!-- 添加/编辑成员弹窗 -->
		<uni-popup ref="popup" type="dialog">



			<uni-popup-dialog :type="popupType" :title="popupTitle" :before-close="true" @close="closeFun"
				:value="popupValue" @confirm="confirmMember" mode="input" :inputValue="formData.name">
				<view class="form-container">
					<uni-forms ref="form" :modelValue="formData" :rules="rules">
						<uni-forms-item label="登录名" name="name" required>
							<uni-easyinput v-model="formData.name" placeholder="请输入登录名" maxlength="20" />
						</uni-forms-item>
						<uni-forms-item label="姓名" name="nickName" required>
							<uni-easyinput v-model="formData.nickName" placeholder="请输入姓名" maxlength="20" />
						</uni-forms-item>
						<uni-forms-item label="手机号" name="phone" required>
							<uni-easyinput v-model="formData.phone" placeholder="请输入手机号" type="number" maxlength="11" />
						</uni-forms-item>
						<uni-forms-item label="角色" name="role" required>
							<uni-data-select v-model="formData.role" :localdata="roleOptions"
								@change="onRoleChange"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item v-if="showAgencyField" label="中介公司" name="agency">
							<uni-data-select v-model="formData.agency" :localdata="agencyOptions"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="密码" name="password" :required="isAdd">
							<uni-easyinput v-model="formData.password" placeholder="请输入密码" type="password"
								maxlength="20" />
						</uni-forms-item>
						<uni-forms-item label="状态" name="status">
							<uni-data-checkbox v-model="formData.status" :localdata="statusOptions" />
						</uni-forms-item>
					</uni-forms>
				</view>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				popupValue: '',
				currentTab: 0,
				tabs: ['全部', '置业顾问', '中介', '个人中介', '前台'],
				members: [],
				filteredMembers: [],
				searchKeyword: '',
				loadStatus: 'more',
				pageSize: 20,
				currentPage: 1,

				// 弹窗相关
				popupType: 'info',
				popupTitle: '添加成员',
				isAdd: true,
				formData: {
					_id: '',
					name: '',
					phone: '',
					role: 3,
					agency: '',
					password: '',
					status: 1
				},
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '请输入登录名'
						}]
					},
					nickName: {
						rules: [{
							required: true,
							errorMessage: '请输入姓名'
						}]
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '请输入手机号'
						}, {
							pattern: '^1[3-9]\\d{9}$',
							errorMessage: '手机号格式不正确'
						}]
					},
					role: {
						rules: [{
							required: true,
							errorMessage: '请选择角色'
						}]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: '请输入密码'
						}, {
							minLength: 6,
							errorMessage: '密码最少6位'
						}, {
							pattern: '^(?![0-9]+$).{6,}$',
							errorMessage: '密码不能全是数字'
						}]
					}
				},
				roleOptions: [{
						value: 3,
						text: '置业顾问'
					},
					{
						value: 4,
						text: '中介'
					},
					{
						value: 5,
						text: '个人中介'
					},
					{
						value: 6,
						text: '前台'
					}
				],
				agencyOptions: [{
						value: '到家了',
						text: '到家了'
					},
					{
						value: '贝壳',
						text: '贝壳'
					},
					{
						value: '其他',
						text: '其他'
					}
				],
				statusOptions: [{
						value: 1,
						text: '启用'
					},
					{
						value: 0,
						text: '禁用'
					}
				],
				height: '500px',
				curMember:{}
			}
		},
		computed: {
			showAgencyField() {
				return this.formData.role === 4; // 只有中介角色显示中介公司字段
			}
		},
		mounted() {
			this.$nextTick(function() {
				setTimeout(() => {
					uni.getSystemInfo({
						success: (resu) => {
							const query = uni.createSelectorQuery()
							query.select('#member').boundingClientRect()
							query.exec(res => {
								console.log(res)
								console.log('resu.windowHeight', resu.windowHeight)
								this.height = resu.windowHeight - res[0].top - 30 +
									'px';
							})
						},
						fail: (res) => {}
					})
				}, 100)
			})
		},
		onLoad() {
			this.loadMembers();
		},
		methods: {
			// 选项卡点击
			onTabClick(e) {
				this.currentTab = e.currentIndex;
				this.filterMembers();
			},

			// 搜索相关
			onSearchInput(e) {
				this.searchKeyword = e.value;
				this.filterMembers();
			},
			search(e) {
				this.searchKeyword = e.value;
				this.filterMembers();
			},

			// 加载成员列表
			async loadMembers() {
				// try {
				const res = await this.$cloudOBjAjax('sunny-users', 'getMemberList', {
					page: this.currentPage,
					pageSize: this.pageSize
				});

				console.log('res', res)

				this.members = res;
				this.filterMembers();
				// } catch (err) {
				// 	console.error('加载成员列表失败:', err);
				// 	uni.showToast({
				// 		title: '加载失败',
				// 		icon: 'none'
				// 	});
				// }
			},

			// 过滤成员
			filterMembers() {
				let filtered = [...this.members];

				// 按角色过滤
				if (this.currentTab > 0) {
					const roleMap = {
						1: 3,
						2: 4,
						3: 5,
						4: 6
					}; // 选项卡索引对应的角色值
					filtered = filtered.filter(member => member.role === roleMap[this.currentTab]);
				}

				// 按搜索关键词过滤
				if (this.searchKeyword) {
					const keyword = this.searchKeyword.toLowerCase();
					filtered = filtered.filter(member =>
						member.name.toLowerCase().includes(keyword) ||
						member.phone.includes(keyword) ||
						(member.agency && member.agency.toLowerCase().includes(keyword))
					);
				}

				this.filteredMembers = filtered;
			},

			// 添加成员
			addMember() {
				this.isAdd = true;
				this.popupTitle = '添加成员';
				this.resetForm();
				this.$refs.popup.open();
			},
			closeFun() {
				this.$refs.popup.close();
				this.$refs.passwordPopup.close()
			},

			// 编辑成员
			editMember(member) {
				this.isAdd = false;
				this.popupTitle = '编辑成员';
				this.formData = {
					_id: member._id,
					name: member.name,
					phone: member.phone,
					role: member.role,
					agency: member.agency || '',
					password: '',
					status: member.status || 1
				};
				this.$refs.popup.open();
			},

			// 显示成员详情
			showMemberDetail(member) {
				uni.showModal({
					title: '成员详情',
					content: `
姓名: ${member.nickName}
手机号: ${member.phone}
角色: ${this.getRoleText(member.role)}
状态: ${member.status === 1 ? '启用' : '禁用'}
${member.agency ? `中介公司: ${member.agency}` : ''}
					`,
					showCancel: false,
					confirmText: '确定'
				});
			},

			// 显示修改密码对话框
			showChangePassword(member) {
				this.curMember = {
					...member
				}

				this.$refs.passwordPopup.open();
			},

			// 复制密码到剪贴板
			copyPassword() {
				let password = this.curMember.password
				uni.setClipboardData({
					data: password,
					success: function() {
						uni.showToast({
							title: '密码已复制',
							icon: 'success'
						});
					},
					fail: function() {
						uni.showToast({
							title: '复制失败',
							icon: 'none'
						});
					}
				});
				this.$refs.passwordPopup.close()
			},

			// confirmChangePassword
			async confirmChangePassword(value) {
				console.log('value', value)

				// 验证密码格式
				if (!value || value.length < 6) {
					uni.showToast({
						title: '密码最少6位',
						icon: 'none'
					});
					return;
				}

				// 验证密码不能全是数字
				if (/^[0-9]+$/.test(value)) {
					uni.showToast({
						title: '密码不能全是数字',
						icon: 'none'
					});
					return;
				}

				// 验证密码不能包含中文
				if (/[\u4e00-\u9fa5]/.test(value)) {
					uni.showToast({
						title: '密码不能包含中文',
						icon: 'none'
					});
					return;
				}

				try {
					await this.$cloudOBjAjax('sunny-users', 'changePassword', {
						userId: this.passwordForm.memberId,
						newPassword: value
					});

					uni.showToast({
						title: '密码修改成功',
						icon: 'success'
					});

					this.$refs.passwordPopup.close();
				} catch (err) {
					console.error('修改密码失败:', err);
					uni.showToast({
						title: err.errorMsg || '修改密码失败',
						icon: 'none'
					});
				}
			},

			// 删除成员
			async deleteMember(member) {
				uni.showModal({
					title: '确认删除',
					content: `确定要删除成员 ${member.name} 吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								await this.$cloudOBjAjax('sunny-users', 'deleteMember', {
									id: member._id
								});

								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});

								this.loadMembers(); // 重新加载列表
							} catch (err) {
								console.error('删除成员失败:', err);
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},

			// 切换成员状态
			async toggleMemberStatus(member) {
				const action = member.status === 1 ? '禁用' : '启用';
				uni.showModal({
					title: '确认操作',
					content: `确定要${action}成员 ${member.name} 吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								const result = await this.$cloudOBjAjax('sunny-users',
									'toggleUserStatus', {
										userId: member._id
									});

								uni.showToast({
									title: result.message,
									icon: 'success'
								});

								this.loadMembers(); // 重新加载列表
							} catch (err) {
								console.error('操作失败:', err);
								uni.showToast({
									title: err.errorMsg || '操作失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},

			// 确认添加/编辑
			async confirmMember() {
				try {
					// 验证表单
					await this.$refs.form.validate();

					const method = this.isAdd ? 'addMember' : 'updateMember';

					await this.$cloudOBjAjax('sunny-users', method, this.formData);

					uni.showToast({
						title: this.isAdd ? '添加成功' : '更新成功',
						icon: 'success'
					});

					this.$refs.popup.close();
					this.loadMembers(); // 重新加载列表
				} catch (err) {
					if (err === 'validation') {
						return;
					}
					console.error('操作失败:', err);
					uni.showToast({
						title: err.errMsg,
						icon: 'none'
					});
				}
			},

			// 角色变更
			onRoleChange(e) {
				if (e !== 4) {
					this.formData.agency = ''; // 非中介角色清空中介公司
				}
			},

			// 重置表单
			resetForm() {
				this.formData = {
					_id: '',
					name: '',
					phone: '',
					role: 3,
					agency: '',
					password: '',
					status: 1
				};
				this.$refs.form?.clearValidate();
			},

			// 工具方法
			getAvatarText(name) {
				return name ? name.charAt(0) : '?';
			},

			getRoleText(role) {
				const roleMap = {
					1: '管理员',
					2: '买家',
					3: '置业顾问',
					4: '中介',
					5: '个人中介',
					6: '前台'
				};
				return roleMap[role] || '未知';
			},

			getRoleColor(role) {
				const colorMap = {
					3: '#3498db', // 置业顾问 - 蓝色
					4: '#9b59b6', // 中介 - 紫色
					5: '#e67e22', // 个人中介 - 橙色
					6: '#2ecc71' // 前台 - 绿色
				};
				return colorMap[role] || '#95a5a6';
			}
		}
	}
</script>

<style scoped>
	.team-page {
		padding: 20rpx;
		background-color: #f8f9fa;
		height: 100%;
	}

	.tabs-container {
		background: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.content {
		background: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
	}

	.action-bar {
		display: flex;
		align-items: center;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}

	.add-btn {
		background: #ff6b35;
		color: #fff;
		border: none;
		border-radius: 4rpx;
		padding: 10rpx 20rpx;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		gap: 8rpx;
		white-space: nowrap;
		height: 36px;
		line-height: 36px;
	}

	.member-list {
		height: calc(100vh - 400rpx);
	}

	.member-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.member-info {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background: #ff6b35;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
	}

	.avatar-text {
		color: #fff;
		font-size: 32rpx;
		font-weight: bold;
	}

	.info-content {
		flex: 1;
	}

	.name-row {
		display: flex;
		align-items: center;
		gap: 16rpx;
		margin-bottom: 8rpx;
	}

	.name {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.role-tag {
		font-size: 20rpx;
		color: #fff;
		padding: 4rpx 12rpx;
		border-radius: 20rpx;
	}

	.phone,
	.agency {
		display: block;
		font-size: 26rpx;
		color: #666;
		margin-bottom: 4rpx;
	}

	.member-status {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		gap: 16rpx;
	}

	.status {
		font-size: 24rpx;
		color: #999;
	}

	.status.online {
		color: #2ecc71;
	}

	.actions {
		display: flex;
		gap: 20rpx;
	}


	::v-deep .uni-dialog-content {
		padding: 20rpx;
	}

	::v-deep .uni-dialog-title-text {
		font-weight: bold;
		color: rgb(255, 107, 53);
	}
</style>